package com.shigen.springcloud.controller;

import com.shigen.springcloud.entity.CommonResult;
import com.shigen.springcloud.entity.Payment;
import com.shigen.springcloud.service.PaymentService;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
@RequestMapping(value = "payment")
public class PaymentController {

  @Value("${server.port}")
  private String port;

  @Resource
  private DiscoveryClient discoveryClient;

  @Resource
  private PaymentService paymentService;

  @PostMapping(value = "create")
  public CommonResult create(@RequestBody Payment payment) {
    log.info("create a payment: {}", payment);
    int result = paymentService.create(payment);
    return result > 0 ? CommonResult.success("成功", null) : CommonResult.error("失败", null);
  }

  @GetMapping(value = "getPayment/{id}")
  public CommonResult getPaymentById(@PathVariable("id") Long id) {
    Payment payment = paymentService.getPaymentById(id);
    return payment != null ? CommonResult.success("成功,当前的port：{}" + port, payment) : CommonResult.error("不存在,当前的port：{}" + port, null);
  }

  @GetMapping(value = "list")
  public CommonResult getDiscoveryClientInfo() {
    discoveryClient.getServices().forEach(log::info);

    List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
    return CommonResult.success(null, instances);
  }

  @GetMapping(value = "lb")
  public String getPort() {
    return port;
  }
}
